package com.itwxz.forum.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.itwxz.common.utils.bean.BeanUtils;
import com.itwxz.common.utils.ip.AddressUtils;
import com.itwxz.common.utils.ip.IpUtils;
import com.itwxz.forum.domain.dto.CommentDto;
import com.itwxz.forum.domain.po.ForumCommentChild;
import com.itwxz.forum.domain.vo.ForumUserInfoVo;
import com.itwxz.forum.service.ForumCommentChildService;
import com.itwxz.forum.mapper.ForumCommentChildMapper;
import com.itwxz.forum.service.ForumPostService;
import com.itwxz.forum.utils.SaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author Admin
* @description 针对表【forum_comment_child(二级评论表)】的数据库操作Service实现
* @createDate 2025-05-13 17:33:49
*/
@Service
@Transactional
public class ForumCommentChildServiceImpl extends ServiceImpl<ForumCommentChildMapper, ForumCommentChild>
    implements ForumCommentChildService{

    @Autowired
    private ForumPostService postService;

    @Override
    public SaResult addChildComment(CommentDto dto) {
        List<String> sensitiveWords = SensitiveWordHelper.findAll(dto.getContent());
        if (!sensitiveWords.isEmpty()) {
            return SaResult.error("评论含敏感词：" + String.join("，", sensitiveWords));
        }

        if (dto.getParentId() == null || dto.getParentId() <= 0)
            return SaResult.error("缺少父评论ID");

        ForumCommentChild comment = BeanUtils.copyBean(dto, ForumCommentChild.class);
        comment.setUserId(StpUtil.getLoginIdAsLong());

        comment.setCreateBy(SaUtils.getNickname());

        String ip = IpUtils.getIpAddr();
        comment.setIp(ip);
        comment.setLocation(AddressUtils.getRealAddressByIP(ip));

        save(comment);

        postService.incrementCommentCount(String.valueOf(comment.getPostId()));

        return SaResult.ok("回复成功");
    }

    @Override
    public SaResult deleteChildComment(String commentId) {
        ForumCommentChild child = getById(commentId);
        if (child == null) return SaResult.error("评论不存在");

        String userId = String.valueOf(child.getUserId());
        if (!StpUtil.getLoginIdAsString().equals(userId))
            return SaResult.error("无权删除评论");

        removeById(commentId);

        postService.decrementCommentCount(String.valueOf(child.getPostId()));

        return SaResult.ok("删除成功");
    }
}




